﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Windows.Forms;
using ExceptionReporting;
using SmartHealthCare.Properties;
using SmartHealthCare.Utils;
using Timer = System.Windows.Forms.Timer;

namespace SmartHealthCare.Frm
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            var login = new FrmLogin();
            DialogResult r = DialogResult.None;
            while (r != DialogResult.OK)
            {
                r = login.ShowDialog(this);
            }
            login.Dispose();
            //
            RevisarPermisos();
            //
            CheckForIllegalCrossThreadCalls = false;
        }

        private void RevisarPermisos()
        {
            var principal = (GenericPrincipal)Thread.CurrentPrincipal;

            if (principal.IsInRole("Admin"))
            {
                toolsMenu.Visible = true;
            }

            if (principal.IsInRole("Reports"))
            {
                reportsToolStripMenuItem.Visible = true;
            }
            if (principal.IsInRole("User"))
            {
                _navBar.Visible = true;
            }
        }

        public List<Form> OpenForms = new List<Form>();
        private readonly Timer _statusTimer = new Timer();


        private void ExitToolsStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }


        private void StatusBarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            statusStrip.Visible = statusBarToolStripMenuItem.Checked;
        }

        private void CascadeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.Cascade);
        }

        private void TileVerticalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileVertical);
        }

        private void TileHorizontalToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.TileHorizontal);
        }

        private void ArrangeIconsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LayoutMdi(MdiLayout.ArrangeIcons);
        }

        private void CloseAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var childForm in MdiChildren)
            {
                childForm.Close();
            }
        }

        private void Main_Load(object sender, EventArgs e)
        {
            ConfigStatusTimer(true);
            RefreshToolStripMenuItemClick(sender, e);
        }


        private void ConfigStatusTimer(bool p)
        {
            _statusTimer.Enabled = p;
            _statusTimer.Interval = 1;
            _statusTimer.Tick += StatusTimerTick;
            _statusTimer.Start();
        }

        private void StatusTimerTick(object sender, EventArgs e)
        {
            _lvlCaps.Text = Console.CapsLock ? "CapsLock On" : "CapsLock Off";
            _lvlNum.Text = Console.NumberLock ? "NumberLock On" : "NumberLock Off";
            //
            _lvlUserName.Text = @" Usuario :" + Environment.UserName;
            _lvlVersion.Text = @" Version: " + Environment.Version;
            _lvlMachine.Text = @" Host: " + Environment.MachineName;
            _lvlDomain.Text = @"Dominio : " + Environment.UserDomainName;
        }

        private void TreeAccionesDoubleClick(object sender, EventArgs e)
        {
            if (_treeAcciones.SelectedNode == null) return;
            var item = _treeAcciones.SelectedNode.Tag;
            if (item == null) return;
            //
            if (Equals(item, "CLIENTE"))
            {
                var frm = new FrmClientes { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "TIPO_CLIENTE"))
            {
                var frm = new FrmClientesTipos { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "TIPO_IDENTIFICACION"))
            {
                var frm = new FrmClientesIdentificacionTipos { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "ASEGURADORA"))
            {
                var frm = new FrmAseguradora { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "TIPO_SEGURO"))
            {
                var frm = new FrmAseguradoraTipoSeguros { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "MEDICOS"))
            {
                var frm = new FrmMedicos { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "PARENTESCOS"))
            {
                var frm = new FrmParentescos { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "CONVERTURA"))
            {
                var frm = new FrmAseguradoraTipoSegurosCovertura { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "SERVICIOS_MEDICOS"))
            {
                var frm = new FrmServiciosMedicos { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "UNIDADES"))
            {
                var frm = new FrmUnidadesTipos { MdiParent = this };
                frm.Show();
            }

            if (Equals(item, "SERVICIOS_X_MEDICOS"))
            {
                var frm = new FrmServiciosMedicosPorMedicos { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "CONSULTA"))
            {
                var frm = new FrmConsultaMedica { MdiParent = this };
                frm.Show();
            }
            if (Equals(item, "HISTORIAL"))
            {
                var frm = new FrmHistorialMedico { MdiParent = this };
                frm.Show();
            }
        }

        private void OptionsToolStripMenuItemClick(object sender, EventArgs e)
        {
            new FrmOptions { MdiParent = this }.Show();
        }

        private void Reportes()
        {
            GetReports(reportsToolStripMenuItem);
        }

        private void GetReports(ToolStripDropDownItem menuItem)
        {
            try
            {
                var service2005 = new ReportingService2005
                                      {
                                          Credentials = new System.Net.NetworkCredential("Administrator", ""),
                                          Url = Settings.Default.ReportsUrl
                                      };
                //
                var list = service2005.ListChildren(Settings.Default.Reportpath, false).ToList();
                list.RemoveAll(i => i.Hidden || (i.Type != ItemTypeEnum.Report && i.Type != ItemTypeEnum.Folder));

                foreach (var item in list)
                {
                    if (item.Type == ItemTypeEnum.Report)
                    {
                        var rName = item.Name.Replace("/", "").Replace("_", " ").ToProperCase().Trim();
                        var rTag = item.Path;
                        var rItem = new ToolStripMenuItem(rName) { Image = Resources.report, Tag = rTag };
                        rItem.Click += ((sender, e) => ShowReports(((ToolStripMenuItem)sender).Tag.ToString()));
                        menuItem.DropDownItems.Add(rItem);
                    }
                    if (item.Type == ItemTypeEnum.Folder)
                    {
                        var rName = item.Name.Replace("/", " ").Replace("_", " ").ToProperCase().Trim();
                        var fItem = new ToolStripMenuItem(rName) { Image = Resources.folder };
                        menuItem.DropDownItems.Add(fItem);
                        GetItems(ref service2005, item, ref fItem);
                    }
                }
            }
            catch (Exception ex)
            {
                var reporter = new ExceptionReporter();
                reporter.ReadConfig();
                reporter.Show(ex);
            }
        }

        private void GetItems(ref ReportingService2005 service2005, CatalogItem item,
                              ref ToolStripMenuItem menuItem)
        {
            var listDependentItems = service2005.ListChildren(item.Path, false).ToList();
            listDependentItems.RemoveAll(
                i => i.Hidden || (i.Type != ItemTypeEnum.Report && i.Type != ItemTypeEnum.Folder));
            //
            foreach (var catalogItem in listDependentItems)
            {
                if (catalogItem.Type == ItemTypeEnum.Report)
                {
                    var rName = catalogItem.Name.Replace("/", " ").Replace("_", " ").ToProperCase().Trim();
                    var rTag = catalogItem.Path;
                    var rItem = new ToolStripMenuItem(rName) { Image = Resources.report, Tag = rTag };
                    rItem.Click += ((sender, e) => ShowReports(((ToolStripMenuItem)sender).Tag.ToString()));
                    menuItem.DropDownItems.Add(rItem);
                    continue;
                }
                if (catalogItem.Type == ItemTypeEnum.Folder)
                {
                    var rName = catalogItem.Name.Replace("/", " ").Replace("_", " ").ToProperCase().Trim();
                    var fItem = new ToolStripMenuItem(rName) { Image = Resources.folder };
                    menuItem.DropDownItems.Add(fItem);
                    //
                    GetItems(ref service2005, catalogItem, ref fItem);
                }
            }
        }

        private void ShowReports(string path)
        {
            FrmBrowser frm;
            bool exist = false;

            OpenForms.ForEach(f => exist = f.GetType() == typeof(FrmBrowser));
            if (exist)
            {
                var b = (FrmBrowser)OpenForms.Where(f => f.GetType() == typeof(FrmBrowser)).First();
                b.AddReport(path);
            }
            else
            {
                frm = new FrmBrowser(path);
                OpenForms.Add(frm);
                frm.MdiParent = this;
                frm.Show();
            }
        }

        private void ReportBuilderToolStripMenuItemClick(object sender, EventArgs e)
        {
            var psi = new ProcessStartInfo
                          {
                              FileName = Settings.Default.ReportServer,
                              WindowStyle = ProcessWindowStyle.Hidden
                          };
            Process.Start(psi);
        }

        private void RefreshToolStripMenuItemClick(object sender, EventArgs e)
        {
            reportsToolStripMenuItem.DropDownItems.Clear();
            reportsToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[]
                                                                {
                                                                    reportBuilderToolStripMenuItem,
                                                                    toolStripSeparator9,
                                                                    refreshToolStripMenuItem,
                                                                    toolStripSeparator10
                                                                });
            var temp = new Thread(Reportes);
            temp.Start();
        }


    }
}
